import pika
import json

def callback(ch, method, properties, body):
    try:
        # 将接收到的 JSON 数据解析
        order_data = json.loads(body.decode('utf-8'))

        # 处理订单数据的业务逻辑
        print("Received order: {}".format(order_data))

        # 在此添加处理订单的业务逻辑，比如写入数据库等操作

        # 手动确认消息
        ch.basic_ack(delivery_tag=method.delivery_tag)

    except json.JSONDecodeError as e:
        print("Error decoding JSON: {}".format(e))
        # 可选择拒绝消息并将其返回到队列，或者执行其他错误处理逻辑
        ch.basic_nack(delivery_tag=method.delivery_tag, requeue=False)

def main():
    connection_params = pika.ConnectionParameters(
        host='localhost',
        virtual_host='order_vhost',
        credentials=pika.PlainCredentials('admin', '123')
    )

    connection = pika.BlockingConnection(connection_params)
    channel = connection.channel()

    # 声明队列
    channel.queue_declare(queue='order_queue', durable=True)

    # 设置消费者回调函数
    channel.basic_consume(
        queue='order_queue',
        on_message_callback=callback,
        auto_ack=False  # 手动确认
    )

    print(' [*] Waiting for orders. To exit press CTRL+C')
    channel.start_consuming()

if __name__ == '__main__':
    main()
